﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntitiesLayer;
using System.Transactions;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using DAL.Repositories;
using DAL.AbstractRepositories;

namespace DAL.Repositorios
{
    public class RolRepository : DAL.AbstractRepositories.AbstractRepository<Rol>
    {
        
        public override void Insert(Rol entity)
        {
            Inserted.Add(entity);
        }

        public override void Delete(Rol entity)
        {
            Deleted.Add(entity);
        }

        public override void Update(Rol entity)
        {
            Updated.Add(entity);
        }
        public override IEnumerable<Rol> GetAll()
        {
            IList<Rol> listaRoles = new List<Rol>();
            SqlCommand cmd = new SqlCommand();
            DataSet ds = DBAccess.ExecuteSPWithDS(ref cmd, "PaListarRoles");

            foreach (DataRow dr in ds.Tables[0].Rows)
                listaRoles.Add(crearRol(dr.Field<int>("IdRol"), dr));

            return listaRoles.Count > 0 ? listaRoles : null;
        }

        public override Rol GetById(int id)
        {
            Rol rol = null;
            SqlCommand cmd = new SqlCommand();
            cmd.Parameters.Add(new SqlParameter("@IdRol", id));
            DataSet ds = DBAccess.ExecuteSPWithDS(ref cmd, "PaConsultarRolPorId");

            foreach (DataRow dr in ds.Tables[0].Rows)
                rol = crearRol(id, dr);

            return rol;   
        }

        
      
        internal static Rol crearRol(int id, DataRow dr){

            return new Rol(
                dr["NombreRol"].ToString(),
                new Lazy<IList<Permiso>>(() =>
                { return RepositoryPermisos.PermisosRol(id);}),
                id
            );
        }

       

        protected override void InsertEntity(Rol objRol){

          
                SqlCommand cmd = new SqlCommand();
                cmd.Parameters.Add(new SqlParameter("@Nombre", objRol.Nombre));

                DBAccess.ExecuteSPNonQuery(ref cmd, "PaRegistrarRol");
            
        }

        protected override void UpdateEntity(Rol objRol)
        {
                SqlCommand cmd = new SqlCommand();
                cmd.Parameters.Add(new SqlParameter("@IdRol", objRol.Id));
                cmd.Parameters.Add(new SqlParameter("@Nombre", objRol.Nombre));

                DBAccess.ExecuteSPNonQuery(ref cmd, "PaModificarRol");
        }

        protected override void DeleteEntity(Rol objRol)
        {
                SqlCommand cmd = new SqlCommand();
                cmd.Parameters.Add(new SqlParameter("@IdRol", objRol.Id));
                DataSet ds = DBAccess.ExecuteSPWithDS(ref cmd, "PaEliminarRol");
        }

    }
}
